package com.framework.wz.wutong.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.framework.wz.wutong.Bean.LoginBean;
import com.framework.wz.wutong.Bean.VersionBean;
import com.framework.wz.wutong.R;
import com.framework.wz.wutong.base.App;
import com.framework.wz.wutong.base.BaseActivity;
import com.framework.wz.wutong.net.RetrofitHelper;
import com.framework.wz.wutong.rx.scheduler.IoMainScheduler;
import com.framework.wz.wutong.utils.AbMd5;
import com.framework.wz.wutong.utils.ConstantUtil;
import com.framework.wz.wutong.utils.DesktopCornerUtil;
import com.framework.wz.wutong.utils.DeviceIdUtil;
import com.framework.wz.wutong.utils.LogUtil;
import com.framework.wz.wutong.utils.OtherUtils;
import com.framework.wz.wutong.utils.PreferenceUtils;
import com.framework.wz.wutong.utils.StatusBarUtil;
import com.framework.wz.wutong.utils.ToastUtil;
import com.framework.wz.wutong.utils.UserManage;
import com.shumai.liveness.LivenessMainActivity;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.vector.update_app.UpdateAppBean;
import com.vector.update_app.UpdateAppManager;
import com.vector.update_app.utils.UpdateAppHttpUtil;

import java.lang.reflect.Method;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class LoginActivity extends BaseActivity {

    @BindView(R.id.et_input1)
    EditText etInput1;
    @BindView(R.id.et_input2)
    EditText etInput2;
    @BindView(R.id.et_input3)
    EditText etInput3;
    @BindView(R.id.btn_login)
    Button btnLogin;
    @BindView(R.id.cb_login)
    CheckBox cbLogin;
    @BindView(R.id.iv1)
    ImageView iv1;

    private static final int START_LIVE_DETECT = 99;

    private boolean hasPermission;
    private String tag;
    private boolean isLogining;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {
//        StatusBarUtil.setStatusBarMode(this, true, R.color.white);
        etInput3.setTransformationMethod(PasswordTransformationMethod.getInstance());
        if (PreferenceUtils.getInstance().getRepw()) {
            cbLogin.setChecked(true);
            boolean autoLogin = true;
            if (!TextUtils.isEmpty(PreferenceUtils.getInstance().getCompanyCode())) {
                etInput1.setText(PreferenceUtils.getInstance().getCompanyCode());
            } else {
                return;
            }
            if (!TextUtils.isEmpty(PreferenceUtils.getInstance().getBianHao())) {
                etInput2.setText(PreferenceUtils.getInstance().getBianHao());
            } else {
                return;
            }
            if (!TextUtils.isEmpty(PreferenceUtils.getInstance().getPASSWORD())) {
                etInput3.setText(PreferenceUtils.getInstance().getPASSWORD());
            } else {
                return;
            }
            if (autoLogin) {
                if (isLogining) {
                    ToastUtil.show(LoginActivity.this, "正在登录，请稍后");
                    return;
                }
                RxPermissions rx = new RxPermissions(LoginActivity.this);
                rx.requestEachCombined(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.READ_PHONE_STATE,
                        Manifest.permission.CAMERA).subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission flag) throws Exception {
                        if (flag.granted) {
                            updateVersion();
//                                login();
                        } else if (flag.shouldShowRequestPermissionRationale) {
                            Toast.makeText(LoginActivity.this, "请授予程序访问存储，相机，定位权限，否则程序无法启动", Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(LoginActivity.this, "请授予程序相应权限", Toast.LENGTH_LONG).show();
                        }
                    }
                });
            }
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {
        /*iv1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                *//*Intent intent = new Intent(LoginActivity.this, LivenessMainActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("actions", "1279"); // 动作组合 1 摇头 2点头 7张嘴 9眨眼
                bundle.putString("actionsNum", "3"); // 检测动作数目

*//**//*******************************
 // UI设置，默认不用设置
 UIConfig config = new UIConfig();
 config.setBottomAreaBgColor("026a86"); // 屏幕下方颜色 026a86
 config.setNoticeTextColor("FFFFFF");   // 动画上方动作提示文字颜色 FFFFFF
 config.setNoticeTextSize("22");        // 动画上方动作提示文字大小 22

 config.setNavTitleColor("FFFFFF");     // 导航栏标题颜色 FFFFFF
 config.setNavBgColor("0186aa");        // 导航栏背景色 0186aa
 config.setNavTitle("活体检测");         // 导航栏标题 活体检测
 config.setNavTitleSize("24");          // 导航栏标题大小 24

 config.setRoundBgColor("004b5e");      // 动画倒计时 进度条背景色 004b5e
 config.setRoundProgressColor("ed7d00");  // 动画倒计时 进度条颜色 ed7d00

 bundle.putSerializable("uiConfig", config);
 *******************************//**//*

                intent.putExtra("liveness", bundle);
                startActivityForResult(intent, START_LIVE_DETECT);*//*
                startActivity(new Intent(LoginActivity.this, LiveCompareActivity.class));
            }
        });*/
    }

    @OnClick({R.id.btn_login, R.id.tv_register})
    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.btn_login:
                if (isLogining) {
                    ToastUtil.show(LoginActivity.this, "正在登录，请稍后");
                    return;
                }
                if (checkParams()) {
                    RxPermissions rx = new RxPermissions(LoginActivity.this);
                    rx.requestEachCombined(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.ACCESS_COARSE_LOCATION,
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.ACCESS_FINE_LOCATION,
                            Manifest.permission.READ_PHONE_STATE,
                            Manifest.permission.CAMERA).subscribe(new Consumer<Permission>() {
                        @Override
                        public void accept(Permission flag) throws Exception {
                            if (flag.granted) {
                                updateVersion();
//                                login();
                            } else if (flag.shouldShowRequestPermissionRationale) {
                                Toast.makeText(LoginActivity.this, "请授予程序访问存储，相机，定位权限，否则程序无法启动", Toast.LENGTH_LONG).show();
                            } else {
                                Toast.makeText(LoginActivity.this, "请授予程序相应权限", Toast.LENGTH_LONG).show();
                            }
                        }
                    });
                }
                break;
            case R.id.tv_register:
                startActivity(new Intent(LoginActivity.this, RegistActivity.class));
                break;
        }
    }

    private boolean checkParams() {
        if (TextUtils.isEmpty(etInput1.getText().toString())) {
            ToastUtil.show(this, "请输入公司代码");
            return false;
        }
        if (TextUtils.isEmpty(etInput2.getText().toString())) {
            ToastUtil.show(this, "请输入员工编号");
            return false;
        }
        if (TextUtils.isEmpty(etInput3.getText().toString())) {
            ToastUtil.show(this, "请输入密码");
            return false;
        }
        return true;
    }

    private void login() {
        showDialog(true);
        final String param1 = etInput1.getText().toString().trim();
        final String param2 = etInput2.getText().toString().trim();
        final String param3 = etInput3.getText().toString().trim();
        String xlh = DeviceIdUtil.getDeviceId(this);
        Log.e("187", "xlh = " + xlh);
        new RetrofitHelper().getApiService(ConstantUtil.BASE_URL).login(param1, param2, param3, xlh).compose(new IoMainScheduler<LoginBean>()).subscribe(new Observer<LoginBean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(LoginBean bean) {
                showDialog(false);
                if (bean == null) {
                    isLogining = false;
                    ToastUtil.show(LoginActivity.this, "系统登录异常，请重试");
                    return;
                }

                if (TextUtils.equals(bean.getStatus(), "200")) {
                    isLogining = false;
                    UserManage.instance().setUid(bean.getUid());
                    rememberPw(param1, param2, param3);
                    String alias = "wu_" + param1 + param2;
                    setAlias(alias);
//                    ToastUtil.show(LoginActivity.this, "登录成功");
                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                    finish();
                } else {
                    isLogining = false;
                    ToastUtil.show(LoginActivity.this, bean.getMessage());
                }
            }

            @Override
            public void onError(Throwable e) {
                isLogining = false;
                ToastUtil.show(LoginActivity.this, "系统登录异常，请重试");
                showDialog(false);
            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void updateVersion() {
        isLogining = true;
        showDialog(true);
        String timestamp = String.valueOf(System.currentTimeMillis());
        String token = AbMd5.MD5(ConstantUtil.TOKEN_KEY + timestamp).toLowerCase();
        String versions = String.valueOf(OtherUtils.getVersion(this));
        new RetrofitHelper().getApiService(ConstantUtil.BASE_URL1).updateVersion(timestamp, token, versions, "1").compose(new IoMainScheduler<VersionBean>()).subscribe(new Observer<VersionBean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(VersionBean bean) {
                showDialog(false);
                if (bean == null) {
                    isLogining = false;
                    return;
                }

                if (TextUtils.equals(bean.getVersyzx(), "2")) {
                    if (TextUtils.equals(bean.getSfqzsj(), "1")) {
                        version("123", true);
                    } else {
                        if (TextUtils.equals(bean.getSfsj(), "1")) {
                            version("1234", false);
                        } else {
                            login();
                        }
                    }
                } else {
                    login();
                }
            }

            @Override
            public void onError(Throwable e) {
                showDialog(false);
            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void version(String url, boolean constraint) {
        final UpdateAppBean mUpdateApp = new UpdateAppBean();
        mUpdateApp.setApkFileUrl(url);
        Log.e("123", Environment.getExternalStorageDirectory() + "/download");
        mUpdateApp.setTargetPath(Environment.getExternalStorageDirectory() + "/download");
        mUpdateApp.setConstraint(constraint);
        new UpdateAppManager
                .Builder()
                //当前Activity
                .setActivity(LoginActivity.this)
                //实现httpManager接口的对象
                .setHttpManager(new UpdateAppHttpUtil(LoginActivity.this))
                .setUpdateUrl(url)
                .setPost(true)
                .build()
                .update(mUpdateApp);
    }

    private void rememberPw(String param1, String param2, String param3) {
        PreferenceUtils.getInstance().setCompanyCode(param1);
        UserManage.instance().setBiaohao(param2);
        PreferenceUtils.getInstance().setPassword(param3);
        if (cbLogin.isChecked()) {
            PreferenceUtils.getInstance().setRepw(true);
        } else {
            PreferenceUtils.getInstance().setRepw(false);
        }
    }

    private void setAlias(String alias) {
        JPushInterface.setAlias(LoginActivity.this,
                101, alias);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == START_LIVE_DETECT) {
            switch (resultCode) { //resultCode为回传的标记，RESULT_OK
                case RESULT_OK:
                    if (null != intent) {
                        Bundle result = intent.getBundleExtra("result");
                        // 错误码, 0检测成功
                        String code = result.getString("code");
                        // 错误信息
                        String msg = result.getString("msg");
                        // 检测通过,code="0"时返回图片保存路径，完整图像
                        String passImgPath = result.getString("passImgPath");
                        // 检测通过,code="0"时返脸部base64，剪裁后的脸部图像
                        String passFace = result.getString("passFace");
                        Log.e("189", "code = " + code);
                        Log.e("189", "msg = " + msg);
                        Log.e("189", "passImgPath = " + passImgPath);
                        Log.e("189", "passFace = " + passFace);
                    }
                    break;
                default:
                    break;
            }
        }
    }

}
